package com.sbtr.security.config;

import com.sbtr.security.common.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * spring security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private CaptchaFilter captchaFilter;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    private JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Value("${server.servlet.context-path}")
    private String basePath;


    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
//        JwtAuthenticationFilter jwtAuthenticationFilter=new JwtAuthenticationFilter(authenticationManager());
//        return jwtAuthenticationFilter;
//    }

    public static String[] URL_WHITELIST;
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        URL_WHITELIST=new String[]{
                "/login",
                "/logout",
                "/captcha",
                "/password",
                "/image/**",
                "/swagger-ui.html/**",
                "/webjars/**",
                "/swagger-resources/**",
                "/csrf/**"
        };
//        for (int i = 0; i <URL_WHITELIST.length ; i++) {
//            URL_WHITELIST[i]=basePath+URL_WHITELIST[i];
//        }
        http
        .cors()
        .and()
        .csrf()
        .disable() // 跨域 csrf攻击关闭

        // 登录配置
        .formLogin()
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
        .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)


        // 禁用session
        .and()
            .sessionManagement()
                 .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        // 配置拦截规则
        .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .antMatchers(HttpMethod.GET,"/","/*.html","/**/*.html","/**/*.js","/**/*.css","/**/*.ico","/**/*.woff","**/*.ttf","/profile/**").permitAll()
                .antMatchers("/swagger-ui.html","swagger-resources/**","/webjars/**","/**").permitAll()
                .anyRequest().authenticated()

        .and()
                .headers().frameOptions().disable()

        // 异常处理器
        .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)

        // 配置自定义过滤器
        .and()
                .addFilterBefore(jwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)

        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService);
    }
}
